<template>
  <div class="app-container">
    <el-tabs v-model="listQuery.status$in" type="card" style="margin-bottom:10px">
      <el-tab-pane
        v-for="item in getOrderStatus()"
        :key="item.value" :label="item.label" :name="item.value+''">
      </el-tab-pane>
    </el-tabs>
    <div class="filter-container">
      <el-input v-model="listQuery.identifier$lk" placeholder="订单编号" class="filter-item" clearable/>
      <el-input v-model="listQuery.originalIdentifier" placeholder="原始订单号" class="filter-item" v-if="type == 10 || type == 11 || type == 12 || type == 13 || type == 14" clearable/>
      <el-input v-model="listQuery.gongyingName$lk" placeholder="供应商名称" v-if="userInfo.type === 1" class="filter-item" clearable/>
      <el-input v-model="listQuery.caigouName$lk" placeholder="采购商名称" v-if="userInfo.type === 2" class="filter-item" clearable/>
      <el-input v-model="listQuery.detail$lk" placeholder="商品名称" class="filter-item" clearable/>
      <el-select v-model="listQuery.invoiceStatus" placeholder="发票状态" clearable class="filter-item">
        <el-option v-for="item in invoiceStatusJson" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <div class="filter-item">
        <div class="searchItem">
          <span class="searchLabel">订单提交时间：</span>
          <DatePicker :mode="1" :startDate.sync="listQuery.createTime$gte" :endDate.sync="listQuery.createTime$lte"
            clearable />
        </div>
      </div>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="success" icon="el-icon-document" @click="handleDownload">
        导出
      </el-button>
    </div>
    
    <el-table ref="table" v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%;" 
    :max-height="tableHeight" :span-method="arraySpanMethod" :cell-style = "cellStyle">
      <el-table-column style="background-color: oldlace;" label="序号" type="index" align="center" width="60px" />
      <el-table-column label="订单编号" prop="identifier" align="center" />
      <el-table-column label="收货人姓名" prop="receiveName" align="center" />
      <el-table-column label="收货人电话" prop="receiveMobile" align="center" />
      <el-table-column label="商品名称" prop="detail" align="center" v-if="type !==14"/><!-- 委托代售不显示 -->
      <el-table-column label="供应商名称" prop="gongyingName" v-if="userInfo.type === 1" align="center" />
      <el-table-column label="采购商名称" prop="caigouName" v-else-if="userInfo.type === 2" align="center" />
      <el-table-column label="实付款" prop="totalAmount" align="center" v-if="type !==14">
        <template slot-scope="{row}">
          <div v-if="row.scoreType && row.scoreType == 2">¥{{ row.totalAmount }}+{{ row.payScore }}积分</div>
          <div v-else-if="row.scoreType && row.scoreType == 1">{{ row.payScore }}积分</div>
          <div v-else>¥{{ row.totalAmount }}</div>
        </template>
      </el-table-column>
      <el-table-column label="订单总数量" prop="totalNum" align="center" v-if="type !==13 && type !==14"/>
      <el-table-column label="商品类型" prop="productTypeText" align="center" />
      
      <!-- <el-table-column v-if="type == 31 && userInfo.type === 2" label="商品底价" prop="allCostPrice" align="center" />
      <el-table-column v-if="type == 31 && userInfo.type === 2" label="一级分润人" prop="dinnerOrderSplitOfflineVo.splitName" align="center" />
      <el-table-column v-if="type == 31 && userInfo.type === 2" label="一级分润金额" prop="dinnerOrderSplitOfflineVo.splitAmount" align="center" />
      <el-table-column v-if="type == 31 && userInfo.type === 2" label="一级奖励金额" prop="dinnerOrderSplitOfflineVo.splitReward" align="center" />
      <el-table-column v-if="type == 31 && userInfo.type === 2" label="二级分润人" prop="dinnerOrderSplitOfflineVo.splitNameSuperior" align="center" />
      <el-table-column v-if="type == 31 && userInfo.type === 2" label="二级奖励金额" prop="dinnerOrderSplitOfflineVo.splitRewardSuperior" align="center" />
      <el-table-column v-if="type == 31 && userInfo.type === 2" label="线下分润明细" prop="dinnerOrderSplitOfflineVo.remark" align="center">
        <template v-if="row.dinnerOrderSplitOfflineVo && row.dinnerOrderSplitOfflineVo.remark" slot-scope="{row}">
          <el-popover
            placement="bottom"
            title="线下分润明细"
            width="200"
            trigger="hover"
            :content="row.dinnerOrderSplitOfflineVo.remark">
            <el-button type="mini" slot="reference">明细</el-button>
          </el-popover>
        </template>
      </el-table-column> -->
      <el-table-column v-if="type == 31 && userInfo.type === 2" label="线上分润明细" prop="splitInfo" align="center">
        <template v-if="row.splitInfo" slot-scope="{row}">
          <el-popover
            placement="bottom"
            title="线上分润明细"
            width="200"
            trigger="hover"
            :content="row.splitInfo">
            <el-button type="mini" slot="reference">明细</el-button>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column label="发票状态" prop="logicId" align="center">
        <template slot-scope="{row}">
          <el-tag v-if="row.invoiceStatus == 1" type="warning">申请发票</el-tag>
          <el-tag v-else-if="row.invoiceStatus == 2" type="success">已上传</el-tag>
          <el-tag v-else type="info">不需要</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" prop="statusText" align="center" v-if="type !==14" />
      <el-table-column label="原始订单号" prop="originalIdentifier" align="center" v-if="type == 10 || type == 11 || type == 12 || type == 13 || type == 14" />
      <el-table-column label="收货类型" prop="logicId" align="center">
        <template slot-scope="{row}">
          <el-tag type="success" v-if="row.logicId == 0">自提</el-tag>
          <el-tag v-else>物流</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="订单提交时间" prop="createTime" align="center"/>
      <el-table-column label="订单付款时间"  prop="payTime" align="center"/>
      <el-table-column label="订单收货时间"  prop="receiveTime" align="center"/>
      <el-table-column label="订单确认时间" prop="handleTime" align="center"/>
      <el-table-column label="订单退款时间" prop="refundTime" align="center"/>
      <el-table-column label="订单退款理由" prop="refundReason" align="center" />
      <el-table-column label="订单物流信息" prop="logicRemark" v-if="type===3" align="center" />
      <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width" width="300px">
        <template slot-scope="{row}">
          <ConfirmOrderButton :type = "type" :order = "row" :userInfo="userInfo"/><!-- 立即支付，确认订单按钮 -->
          
          <!-- 申请退款 -->
          <el-button type="primary" size="mini" @click="mallRefund(row)"
            v-if="(type=== 1|| type=== 11||type=== 12||type=== 10 ||type=== 13 || type=== 7 || type=== 31) && (row.status===2||row.status===3) && userInfo.type ===1">申请退款
          </el-button>

          <!-- 供应商 确认退款 -->
          <el-button type="primary" size="mini" @click="mallRefundConfirm(row,true)"
            v-if="(type=== 1|| type=== 11||type=== 12||type=== 10 ||type=== 13 || type=== 7 || type=== 31) && row.status===7 && userInfo.type ===2">
            确认退款</el-button>
          
          <!-- 供应商 拒绝退款 -->
          <el-button type="danger" size="mini" @click="mallRefundConfirm(row)"
            v-if="(type=== 1|| type=== 11||type=== 12||type=== 10 ||type=== 13 || type=== 7 || type=== 31) && row.status===7 && userInfo.type ===2">拒绝退款
          </el-button>

          <CancelButton :row="row" :userInfo="userInfo" :orderStatusJson="orderStatusJson"
            :orderTypeJson="orderTypeJson" @handleCancel="handleCancel" /><!-- 取消订单 -->

          <!-- 立即发货/立即收货/ -->
          <MallSendButton :row="row" :userInfo="userInfo" :orderStatusJson="orderStatusJson"
            :orderTypeJson="orderTypeJson" @getList="getList"/>
            <!-- row.logicId > 0 为自提 -->
						<el-button type="primary" size="mini" @click="mallLogistics(row, false)"
						  v-if="(type != 8) && (row.status != 1 && row.status != 2) && row.logicId > 0">查看物流
						</el-button>
            <el-button type="primary" size="mini" @click="mallEvaluate(row)"
              v-if="(type=== 1|| type=== 11||type=== 12||type=== 10 ||type=== 13 || type=== 7 || type=== 31) && row.status===4 && userInfo.type ===1">评价
            </el-button>

          <!-- 小程序订单 退货申请 -->
          <el-button v-if="(type=== 7 || type === 31) && row.status === 9 && userInfo.type ===2" type="primary" size="mini" @click="returnGood(row,true)">同意退货
					</el-button>
          <el-button v-if="(type=== 7 || type === 31) && row.status === 9 && userInfo.type ===2" type="danger" size="mini" @click="returnGood(row, false)">不同意退货
					</el-button>

          <!-- 小程序订单 退货中-->
          <el-button v-if="(type=== 7 || type === 31) && row.status === 10 && userInfo.type ===2" type="primary" size="mini" @click="confirmRefund(row)">确认退款
					</el-button>
          <el-button v-if="(type=== 7 || type === 31) && row.status === 10" type="success" size="mini" @click="mallLogistics(row, true)">查看物流
					</el-button>

          <!-- 众茶通小程序/商城订单 待付款-->
          <el-button v-if="(type === 1 ||type=== 7) && row.status === 1 && userInfo.type ===2" type="primary" size="mini" @click="editPrice(row)">修改价格
					</el-button>

          <OrderDetailButton :order = "row"/><!-- 订单详情按钮 -->

          <!-- 打印订单 -->
          <el-button v-if="(row.type == 31 || row.type == 35) && row.status === 2 && row.cartType == 1 && userInfo.type === 2" type="warning" size="mini" @click="handlePrintDialog(row)">打印订单</el-button>

          <!-- 线上下德邦快递单 -->
          <el-button v-if="(row.type == 31 || row.type == 35) && row.status === 2 && row.cartType == 1 && row.logicId != 0 && userInfo.type === 2" size="mini" @click="handelDBExpress(row)">德邦快递</el-button>

          <!-- 上传发票 -->
          <el-button v-if="row.invoiceStatus && row.invoiceStatus == 1" type="warning" size="mini" @click="handleInvoiceDialog(row)">上传发票</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize"
      @pagination="getList" />

		<el-dialog title="物流信息" append-to-body :visible.sync="dialogLogistics" width="600px">
			<iframe id="mapPage" width="100%" height="280px" frameborder=0
				:src="logisticsList.trailUrl">
			</iframe>
			<div style="height: auto;">
			  <el-steps direction="vertical" :active="1">
			    <el-step :title="item.status" :description="item.context" v-for="(item,imdex) in logisticsList.data" :key="imdex"></el-step>
			  </el-steps>
			</div>
		</el-dialog>

    <el-dialog title="商品评价" :visible.sync="dialogEvaluate" width="600px">
    	<div>
        <div style="display: flex;align-items: center;padding: 10px 0;">
          <span style="padding-right: 10px;">描述相符</span>
          <el-rate v-model="Evaluate.productScore" :texts="texts" show-text></el-rate>
        </div>
        <div class="Upload">
          <UpImgs :default-image.sync="images" :limit="9" />
          <!-- <Upload :default-image.sync="imgs" :mode="5"/> -->
        </div>
        <el-input style="margin-top: 10px;" v-model="Evaluate.content" type="textarea" placeholder="请输入内容"></el-input>
        <div style="margin-top: 10px;" >供应商名称：{{ Evaluate.gongyingName }}</div>
        <div style="display: flex;align-items: center;padding: 10px 0;">
          <span style="padding-right: 10px;">服务评价</span>
          <el-rate v-model="Evaluate.serviceScore" :texts="texts" show-text></el-rate>
        </div>
        <div style="display: flex;align-items: center;padding: 10px 0;">
          <span style="padding-right: 10px;">物流评价</span>
          <el-rate v-model="Evaluate.logisticsScore" :texts="texts" show-text></el-rate>
        </div>
    	</div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEvaluate = false">取消</el-button>
        <el-button type="primary" @click="confirmOrderEvaluate()">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改价格" :visible.sync="editPriceDialogVisible">
      <el-form ref="dataForm" :rules="rules" :model="editPriceForm" label-position="right" label-width="88px"
        style="margin: 0 50px;">
        <el-form-item label="订单价格" prop="newPrice">
          <el-input type="text" v-model="editPriceForm.newPrice"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editPriceDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="saveNewPrice()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="打印订单" v-if="printOrderDialogVisible" append-to-body :visible.sync="printOrderDialogVisible" width="800px">
      <el-button style="float: right;" type="primary" @click="doPrint">打印订单</el-button>
			<iframe ref="printIframe" id="iframe" width="100%" height="600px" frameborder=0
				:src="printOrderUrl">
			</iframe>
		</el-dialog>

    <el-dialog title="德邦快递" v-if="dbExpressDialogVisible" :visible.sync="dbExpressDialogVisible">
      <el-form ref="dbexpressform" :rules="dbRules" :model="dbExpressForm" label-position="right" label-width="120px">
        <el-form-item label="运输方式">
          <el-input type="text" value="标准快递" disabled></el-input>
        </el-form-item>
        <el-form-item label="结算方式">
          <el-input type="text" value="月结" disabled></el-input>
        </el-form-item>
        <el-form-item label="总件数">
          <el-input type="text" value="1件" disabled></el-input>
        </el-form-item>
        <el-form-item label="货物名称" prop="cargo">
          <el-input type="text" v-model="dbExpressForm.cargo"></el-input>
        </el-form-item>
        <el-form-item label="总重量(公斤)" prop="weight">
          <el-input type="text" v-model="dbExpressForm.weight"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="text" v-model="dbExpressForm.remark"></el-input>
        </el-form-item>
        <el-form-item label="收件人">
          <el-input type="text" :value="orderDetail.caigouName" disabled></el-input>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input type="text" :value="orderDetail.caigouMobile" disabled></el-input>
        </el-form-item>
        <el-form-item label="详细地址">
          <el-input type="text" :value="orderDetail.allAddress" disabled></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dbExpressDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="sendDbExpress()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="上传发票" v-if="invoiceDialogVisible" append-to-body :visible.sync="invoiceDialogVisible" width="600px">
			<el-card class="box-card" shadow="hover">
        <div slot="header" class="clearfix">
          <span>发票详情</span>
        </div>
        <el-row>
          <el-col :span="24">
            <div class="invoice_bg">
              <div>
                <span class="title">类型：</span>
                <span v-if="invoiceDetail.type == 1" class="content">企业</span>
                <span v-else class="content">个人</span>
              </div>
              <div>
                <span class="title">发票抬头：</span>
                <span class="content">{{invoiceDetail.invoiceName}}</span>
              </div>
              <div>
                <span class="title">企业税号：</span>
                <span class="content">{{invoiceDetail.invoiceNo}}</span>
              </div>
              <div>
                <span class="title">企业地址：</span>
                <span class="content">{{invoiceDetail.invoiceAddress}}</span>
              </div>
              <div>
                <span class="title">联系电话：</span>
                <span class="content">{{invoiceDetail.invoicePhone}}</span>
              </div>
              <div>
                <span class="title">开户银行：</span>
                <span class="content">{{invoiceDetail.invoiceBank}}</span>
              </div>
              <div>
                <span class="title">银行账户：</span>
                <span class="content">{{invoiceDetail.invoiceBankNo}}</span>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <el-upload
        class="upload-demo"
        ref="upload"
        action=""
        
        :limit="1"
        :auto-upload="false">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <div slot="tip" class="el-upload__tip">只能上传1张</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="invoiceDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="uploadInvoice()">
          确定
        </el-button>
      </div>
		</el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  orderPageByQo, orderCancel, orderHandle, orderStatusJson, orderMallStatusJson, entrustSellStatusJson, orderDeliverStatusJson, wxOrderStatusJson, 
  orderTypeJson, orderGetById, orderCreate, mallRefundApply, mallRefundConfirm, queryLogInfo,CommentReleaseComment, mallOrderConfirm, entrustBuyStatusJson, 
  agreeReturnGood, disagreeReturnGood, requestConfirmRefund, queryTuiKuanLogInfo, changeOrderPrice, scanOrderStatusJson, zcyxOrderStatusJson,
  orderGetFZById, getExpressOrder, getInvoiceByOrderId
} from '@/api/mall'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination'
import CancelButton from './CancelButton'
import MallSendButton from './MallSendButton'
import Upload from '@/components/Upload'
import UpImgs from '@/components/Upload/UpImgs'
import NumInput from '@/components/NumInput'
import DatePicker from '@/components/DatePicker'
import qs from 'qs'
import OrderDetailButton from '@/views/mall/order/components/OrderDetailButton'
import ConfirmOrderButton from '@/views/mall/order/components/ConfirmOrderButton'
import updateTableMixin from '@/mixin/updateTable'
import request from '@/utils/request'
import { BASEURL } from '/public/static/config.js'

// type 值
// 1 众茶通APP订单
// 2 提货单
// 3 发货单
// 4 退货单
// 5 对账单
// 6 结算单
// 7 众茶通小程序订单
// 8 扫码支付订单
// 10 集采交易订单
// 11 挂牌交易订单
// 12 竟价交易订单
// 13 委托代购订单
// 14 委托代售订单
// 20 集采定金单
// 21 竞价定金单
// 30 微商城订单
// 31 众茶优选订单
// 35 众茶优选积分订单
// 60 分润单
// 61 众茶优选分润单


export default {
  name: "Order",
  directives: { waves },
  components: { Pagination, CancelButton, MallSendButton, Upload, UpImgs, NumInput, DatePicker, OrderDetailButton, ConfirmOrderButton },
  mixins: [updateTableMixin],
  props: {
    type: {
      default: 1,
      type: Number,
    },
  },
  data() {
    return {
      list: [],
      allList: [],
      total: 0,
      listLoading: true,
      downloadLoading: false,
      listQuery: {
        pageNo: 1,
        pageSize: 20,
        type: '',
        status$in: '0',
        identifier$lk: '',
        originalIdentifier: '',
        gongyingName$lk: '',
        caigouName$lk: '',
        createTime$gte: '',
        createTime$lte: '',
        detail$lk: '',
        splitSupplier$lk: '',
        isBackend: 1
      },
      allListQuery: {
        pageNo: 1,
        pageSize: 20,
        type: '',
        status$in: '0',
        identifier$lk: '',
        originalIdentifier: '',
        gongyingName$lk: '',
        caigouName$lk: '',
        createTime$gte: '',
        createTime$lte: '',
        detail$lk: '',
        splitSupplier$lk: '',
        isBackend: 1
      },
      temp: {
        id: 0,
        remark: "",
        image: "",
        status: 1
      },
      dialogFormVisible: false,
      dialogDetailVisible: false,
			dialogLogistics:false,
      dialogEvaluate:false,
      editPriceDialogVisible:false,
      editPriceForm: {
        newPrice: ''
      },
			logisticsList:[],
      Evaluate:{
        productScore:null,
        logisticsScore:null,
        serviceScore:null,
        imgs:'',
        content:'',
        orderId:'',
        productId:'',
        gongyingName:'',
      },
      texts:['非常不满意', '不满意', '一般', '满意', '非常满意'],
      images:[],
      rules: {
        remark: [{ required: true, message: "请输入", trigger: "blur" }],
      },
      orderTypeJson: orderTypeJson(),
      orderStatusJson: orderStatusJson(),
      orderMallStatusJson: orderMallStatusJson(),
      entrustBuyStatusJson: entrustBuyStatusJson(),
      entrustSellStatusJson: entrustSellStatusJson(),
      orderDeliverStatusJson: orderDeliverStatusJson(),
      wxOrderStatusJson: wxOrderStatusJson(),
      scanOrderStatusJson: scanOrderStatusJson(),
      zcyxOrderStatusJson: zcyxOrderStatusJson(),
      rowArray:[],
      colorFlagArray:[],
      printOrderDialogVisible: false,
      printOrderUrl: "",
      parentOrder:{},
      dbExpressDialogVisible:false,
      dbExpressForm: {
        orderId:'',
        cargo: '茶叶',
        weight: '1',
        remark: '',
        type: 1 // 1: 优选订单，2：积分订单
      },
      dbRules: {
        cargo: [{ required: true, message: "请输入", trigger: "blur" }],
        weight: [{ required: true, message: "请输入", trigger: "blur" }]
      },
      orderDetail:{},
      invoiceDialogVisible: false,
      invoiceOrder: {},
      invoiceDetail: {},
      invoiceStatusJson: [
        { value: 0, label: '不需要' },
        { value: 1, label: '申请发票' },
        { value: 2, label: '已上传' }
      ],
    }
  },
  computed: {
    ...mapGetters(["userInfo"]),
    getOrderStatus() {
      if (this.type == 1) {
        return orderMallStatusJson
      } else if (this.type == 13) {
        return entrustBuyStatusJson
      } else if (this.typepe == 14) {
        return entrustSellStatusJson
      } else if (this.type == 7) {//微信小程序
        return wxOrderStatusJson
      } else if (this.type == 3) {
        return orderDeliverStatusJson
      } else if (this.type == 30) {//微商城
        return wxOrderStatusJson
      } else if (this.type == 8) {//扫码支付订单
        return scanOrderStatusJson
      } else if (this.type == 31) {//众茶优选订单
        return zcyxOrderStatusJson
      } else {
        return orderStatusJson
      }
    }
  },
  watch: {
    'listQuery.status$in': function () {
      this.handleFilter()
    },
    'temp.status': function (val) {
      this.temp.remark = val ? '同意' : '驳回';
    },
    imgs(val) {
      if (val && val.length) {
        this.Evaluate.imgs = val.map(item => {
          return item.url
        }).join(',');
      } else {
        this.Evaluate.imgs = '';
      }
    },
    $route: {
      handler: function(route) {
        const t = route.query.t;
        if (t) {
          if (this.$route.query.status && this.listQuery.status$in !== this.$route.query.status.toString()) {
            this.listQuery.status$in = this.$route.query.status.toString()
          }
          if (this.$route.query.identifier) {
            this.listQuery.identifier$lk = this.$route.query.identifier.toString();
          }
          this.handleFilter()
        }
      },
      immediate: true
    }
  },
  created() {
    this.listQuery.type = this.type

    if (this.$route.query.status && this.listQuery.status$in !== this.$route.query.status.toString()) {
      this.listQuery.status$in = this.$route.query.status.toString()
    }
    if (this.$route.query.identifier) {
      this.listQuery.identifier$lk = this.$route.query.identifier.toString();
    }

    this.getList()

    let that = this
    window.addEventListener('message', function (message) {
      if (message.data.status == 'isReady') {
        if (that.printOrderDialogVisible && that.parentOrder && that.parentOrder.id) {
          that.getPrintOrder()
        }
      }
    })
  },
  methods: {
    updateRowArray() {
      if (this.type == 31) {
        this.rowArray = []
        this.colorFlagArray = []

        var id_pos = 0
        for (let index = 0; index < this.list.length; index++) {
          if (index == 0) {
            this.rowArray.push(1)
            this.colorFlagArray.push(1)
          } else {
            var current = this.list[index].scoreParentOrderId
            var last = this.list[index - 1].scoreParentOrderId
            if (current && last && (current == last)) {
              this.rowArray[id_pos] = this.rowArray[id_pos] + 1
              this.rowArray.push(0)
              
              let flag =  this.colorFlagArray[index - 1]
              this.colorFlagArray.push(flag)
            } else {
              this.rowArray.push(1)
              id_pos = index

              let flag =  this.colorFlagArray[index - 1] == 1 ? 2 : 1
              this.colorFlagArray.push(flag)
            }
          }
        }
      }
    },
    cellStyle({row, column, rowIndex, columnIndex}) {
      if (this.type == 31) {
        if (columnIndex == 0) {
          if (this.colorFlagArray[rowIndex] == 1) {
            return "background: oldlace;"
          } else {
            return "background: #f0f9eb;"
          }
        }
      }
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (this.type == 31) {
        if (columnIndex === 0) {
          let row = this.rowArray[rowIndex]
          if (row > 0) {
            return {
              rowspan: row,
              colspan: 1
            };
          } else {
            return {
              rowspan: 0,
              colspan: 0
            };
          }
        }
      }
    },
    // 查看物流
		mallLogistics(row, type){// type 小程序退货中 true 其余为false
      if (type) {
        queryTuiKuanLogInfo({id:row.id}).then(res=>{
          if (!res.result && res.message && !res.message === "ok") {
            this.$message.error(res.message)
          }
          this.logisticsList = res;
          this.dialogLogistics = true;
        }).catch(err=>{
          console.log(err);
        })
      } else {
        queryLogInfo({id:row.id}).then(res=>{
          if (!res.result && res.message && !res.message === "ok") {
            this.$message.error(res.message)
          }
          this.logisticsList = res;
          this.dialogLogistics = true;
        }).catch(err=>{
          console.log(err);
        })
      }
			
		},
    // 评价
    mallEvaluate(row){
      this.dialogEvaluate = true;
      this.Evaluate.orderId = row.id;
      this.Evaluate.productId = row.detailList[0].productId
      this.Evaluate.gongyingName = row.gongyingName;
    },
    confirmOrderEvaluate(row){
      if(this.Evaluate.productScore == null){
        this.$message.error('请对商品进行评分')
        return
      }
      CommentReleaseComment(this.Evaluate).then(res=>{
        this.dialogEvaluate = false;
        this.getList();

        this.$message({
          message: '评价成功',
          type: 'success'
        });
      })
    },
    getList() {
      this.listLoading = true;

      let params = Object.assign({}, this.listQuery);
      if (params.status$in === '0') {
        params.status$in = '';
      }
      if (params.status$in == 100) {
        params.status$in = '4,6'
      }

      orderPageByQo(params).then((response) => {
        this.list = response.list || [];
        this.total = response.totalCount;
        this.listLoading = false;
        this.handleSplitDataToText(this.list)
        
        this.updateTableHeight()
        this.updateRowArray()
      }).catch(error => {
        console.log(error)
        this.listLoading = false;
      });
    },
    getAllList() {
      this.listLoading = true;

      this.allListQuery = Object.assign({}, this.listQuery);
      this.allListQuery.pageNo = 1;
      this.allListQuery.pageSize = this.total

      let params = Object.assign({}, this.allListQuery);
      if (params.status$in === '0') {
        params.status$in = '';
      }
      if (params.status$in == 100) {
        params.status$in = '4,6'
      }

      return new Promise((resolve, reject) => {
        orderPageByQo(params).then((response) => {
          this.allList = response.list || []
          this.listLoading = false

          this.handleSplitDataToText(this.allList)
          resolve(true)
        }).catch(error => {
          console.log(error)
          this.listLoading = false
          reject(false)
        });
      })
    },
    handleFilter() {
      this.listQuery.pageNo = 1;
      this.getList();
    },
    handleSplitDataToText(dataList) {
      for (let index = 0; index < dataList.length; index++) {
        var element = dataList[index];

        var splitInfo = ''
        if (element.splitSuppliers && element.splitSuppliers.length > 0) {
          for (let j = 0; j < element.splitSuppliers.length; j++) {
            const item = element.splitSuppliers[j];
            
            var type = ''
            if (item.splitType == 1) {
              type = '(供货供应商)'
            } else if (item.splitType == 2) {
              type = '(分润供应商)'
            } else {
              type = '(当前商家)'
            }

            var name = '名称：' + item.splitName + type + '，'
            var splitRate = ''
            if (item.splitType == 1) {
              splitRate = ''
            } else {
              splitRate = '分润比例：' + item.splitRate + '，'
            }
            var splitAmount = '分润金额：' + item.splitAmount
            var result = name + splitRate + splitAmount
            var temp = j > 0 ? '；' : ''
            
            splitInfo = splitInfo + temp + result
          }
        }

        this.$set(element, 'splitInfo', splitInfo)
      }
    },
    handleDownload() {
      this.getAllList().then(res => {
        if (this.allList.length <= 0) {
          return;
        }

        let tHeader = []
        let filterVal = []
        
        tHeader = ['订单编号', '商品名称','采购商名称','采购商电话', '供应商名称', '供应商电话', '实付款', '积分','订单总数量', '商品类型',
        '订单状态','原始订单号', '收货类型','订单提交时间', '订单付款时间','订单确认时间', '订单收货时间','订单退款时间','订单退款理由',
        '收货人', '电话', '省', '城市', '县/区', '详细地址', '订单类型', '快递公司', '快递单号', '订单留言', '委托说明']
        filterVal = ['identifier', 'detail', 'caigouName', 'caigouMobile', 'gongyingName', 'gongyingMobile' , 'totalAmount', 'payScore', 'totalNum', 'productTypeText', 
        'statusText','originalIdentifier', 'logicId','createTime','payTime','handleTime', 'receiveTime', 'refundTime','refundReason',
        'receiveName', 'receiveMobile', 'receiveProvinceName', 'receiveCityName', 'receiveDistrictName', 'receiveAddress', 'typeText', 'logicRemark', 'logicNo', 'remark', 'entrustRemark']
        
        if (this.type == 31) { // 众茶优选订单
          if (this.userInfo.type === 2) {
            this.addDataToHeader(tHeader, filterVal, ['商品底价', 'allCostPrice'])
            this.addDataToHeader(tHeader, filterVal, ['线上分润明细', 'splitInfo'])
            
            // this.addDataToHeader(tHeader, filterVal, ['一级分润人', 'dinnerOrderSplitOfflineVo.splitName'])
            // this.addDataToHeader(tHeader, filterVal, ['一级分润金额', 'dinnerOrderSplitOfflineVo.splitAmount'])
            // this.addDataToHeader(tHeader, filterVal, ['一级奖励金额', 'dinnerOrderSplitOfflineVo.splitReward'])
            // this.addDataToHeader(tHeader, filterVal, ['二级分润人', 'dinnerOrderSplitOfflineVo.splitNameSuperior'])
            // this.addDataToHeader(tHeader, filterVal, ['二级奖励金额', 'dinnerOrderSplitOfflineVo.splitRewardSuperior'])
            // this.addDataToHeader(tHeader, filterVal, ['线下分润明细', 'dinnerOrderSplitOfflineVo.remark'])
          }
        }
        
        if (this.userInfo.type === 2) {
          this.addDataToHeader(tHeader, filterVal, ['经纪人专区服务费比例', 'serviceRate'])
          this.addDataToHeader(tHeader, filterVal, ['经纪人专区服务费服务费', 'totalServiceAmount'])
        }
        
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const list = this.allList
          const data = this.formatJson(filterVal, list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: "订单列表",
            autoWidth: true,
            bookType: "xlsx"
          })
          this.downloadLoading = false
        })
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => {
        return filterVal.map(j => {
          if (j.indexOf("dinnerOrderSplitOfflineVo.") != -1) {
            let obj = j.split('.')[0]
            let value = j.split('.')[1]
            if (v[obj]) {
              return v[obj][value]
            } else {
              return ''
            }
          } else if (j === 'logicId') {
            if (v[j] == 0) {
              return '自提'
            } else {
              return '物流'
            }
          } else {
            return v[j]
          }
        })
      })
    },
    addDataToHeader(header, filterVal, list) {
      header.push(list[0])
      filterVal.push(list[1])
    },
    handleCancel(row) {
      this.$confirm("是否确认取消订单？").then(() => {
        orderCancel({ id: row.id }, this.type === 1).then(() => {
          this.getList();

          this.$message({
            message: '操作成功',
            type: 'success'
          });
        });
      });
    },
    getDetail(id) {
      return new Promise((resolve, reject) => {
        orderGetById({ id: id })
          .then(res => {
            resolve(res);
          })
          .catch(err => {
            reject(err);
          });
      });
    },
    mallRefund(row) {
      this.$prompt('退款理由', '退款', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator(value) {
          return value ? true : false
        },
        inputErrorMessage: '请输入退款理由'
      }).then(({ value }) => {
        mallRefundApply({ id: row.id, refundReason: value }).then(() => {

          this.$message({
            message: '操作成功',
            type: 'success'
          });
          this.getList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消退款操作'
        });
      });
    },
    mallRefundConfirm(row, isConfirm) {
      this.$confirm(`是否${isConfirm ? '确认' : '拒绝'}退款？`).then(() => {
        mallRefundConfirm(row.id, isConfirm).then(() => {

          this.$message({
            message: '操作成功',
            type: 'success'
          });
          this.getList()
        })
      })
    },  
    //小程序订单 退货申请
    returnGood(row, status) {
      if (status) {
        this.$confirm("请确认是否同意退货？").then(() => {
          agreeReturnGood({ id: row.id}).then(response => { 
            this.$message.success("操作成功")
            this.getList()
          }).catch(error => {
            console.log(error);
          })
        });
      } else {
        this.$confirm("请确认是否不同意退货？").then(() => {
          disagreeReturnGood({ id: row.id}).then(response => { 
            this.$message.success("操作成功")
            this.getList()
          }).catch(error => {
            console.log(error);
          })
        });
      }
    },
    // 小程序订单 退货中 确认退款
    confirmRefund(row) {
      this.$confirm("请确认是否同意退款？").then(() => {
        requestConfirmRefund({ id: row.id }).then(response => { 
          this.$message.success("操作成功")
          this.getList()
        }).catch(error => {
          console.log(error);
        })
      });
    },
    // 小程序订单 待付款 修改价格
    editPrice(row) {
      this.editPriceDialogVisible = true
      this.editPriceForm.orderId = row.id
      this.editPriceForm.newPrice = ''
    },
    saveNewPrice() {
      changeOrderPrice(this.editPriceForm).then(response => { 
        this.$message.success("操作成功")
        this.editPriceDialogVisible = false
        this.getList()
      }).catch(error => {
        console.log(error);
      })
    },
    doPrint() {
      var printFrame = this.$refs['printIframe'];
      printFrame.contentWindow.postMessage(
        {option: 'doPrint'},
        '*'
      );
    },
    handlePrintDialog(row) {
      this.printOrderDialogVisible = true
      this.printOrderUrl = "https://utea88.com/static/printOrder/index.html"
      this.parentOrder = row
    },
    getPrintOrder() {
      orderGetFZById({ id: this.parentOrder.id }).then(res => {
        var printFrame = this.$refs['printIframe'];
        printFrame.contentWindow.postMessage(
          {type: 31, data: res},
          '*'
        );
      }).catch(err => {
        console.log(err)
      })
    },
    handelDBExpress(row) {
      this.dbExpressForm = {
        orderId:'',
        cargo: '茶叶',
        weight: '1',
        remark: '',
        type: 1
      }
      orderGetById({ id: row.id }).then(res => {
        this.orderDetail = Object.assign({}, res)
        if (this.orderDetail.label && this.orderDetail.label.length > 0) {
          this.printOrderDialogVisible = true
          this.printOrderUrl = "https://utea88.com/static/printOrder/index.html?expressUrl=" + this.orderDetail.label
        } else {
          this.dbExpressForm.orderId = this.orderDetail.id

          var allAddress = this.orderDetail.receiveProvinceName 
          + " " + this.orderDetail.receiveCityName 
          + " " + this.orderDetail.receiveDistrictName 
          + " " + this.orderDetail.receiveAddress
          this.$set(this.orderDetail, 'allAddress', allAddress)

          this.dbExpressDialogVisible = true
        }
      }).catch(err => {
        console.log(err)
      })
    },
    sendDbExpress() {
      this.$refs['dbexpressform'].validate((valid) => {
        if (valid) {
          getExpressOrder(this.dbExpressForm).then(res => {
            this.dbExpressDialogVisible = false
            this.printOrderDialogVisible = true
            this.printOrderUrl = "https://utea88.com/static/printOrder/index.html?expressUrl=" + res
          })
          .catch((err) => {
            console.log(err)
          })
        }
      })
    },
    handleInvoiceDialog(row) {
      this.invoiceDialogVisible = true
      this.invoiceOrder = row
      getInvoiceByOrderId({ orderId: row.id }).then(res => {
        this.invoiceDetail = res
      })
      .catch((err) => {
        console.log(err)
      })
    },
    uploadInvoice() {
      if (this.$refs.upload.uploadFiles.length > 0) {
        var formData = new FormData();
        formData.append('orderId', this.invoiceOrder.id)
        formData.append('multipartFile', this.$refs.upload.uploadFiles[0].raw)

        request({
          url: (process.env.BASE_URL || BASEURL) + '/dinner/order/uploadInvoice',
          data: formData,
          method: 'post',
          headers:{'Content-Type': 'multipart/form-data'},
        }).then(res => { 
          this.$message.success('操作成功')
          this.invoiceDialogVisible = false
          this.handleFilter()
        }).catch(error => {
          console.log(error);
        })
      }
    }
  },
}
</script>
<style lang="scss" scoped>
.el-row {
  line-height: 2;
  font-size: 15px;
}
.searchItem {
  display: flex;
  align-items: center;
  .searchLabel {
    color: #666;
  }
}
.box-card {
  margin: 20px 0;
  .flexItem {
    display: flex;
    align-items: center;
    .fuhao {
      margin-right: 3px;
      font-size: 16px;
      color: red;
    }
    .el-input {
      width: auto;
      flex: 1;
    }
  }
}
</style>
